<template>
  <el-form :model="{questions}" label-position="top" class="bold-label">
    <el-form-item v-for="(question, index) in questions" :key="question.index"
                  :ref="initQuestionRef(question)" class="question-item"
                  :label="`${index + 1}. ${question.title || '标题'}`">
      <el-radio-group v-if="question.type === 1" v-model="answers[index]"
                      class="column">
        <el-radio v-for="(option, idx2) in question.options" :key="option.index"
                  :ref="initOptionRef(question, option)" :label="option.index">
          {{ option.title || `选项${idx2 + 1}`}}
          <template v-if="option.fill">
            <el-input v-if="answers[index] === option.index" v-model="fills[index][option.index]"
                      @click.native="selectItem($event, question, option)"/>
            <el-input v-else @click.native="selectItem($event, question, option)"/>
          </template>
        </el-radio>
      </el-radio-group>
      <el-checkbox-group v-if="question.type === 2" v-model="answers[index]"
                         class="column">
        <el-checkbox v-for="(option, idx2) in question.options" :key="option.index"
                     :ref="initOptionRef(question, option)" :label="option.index">
          {{ option.title || `选项${idx2 + 1}`}}
          <template v-if="option.fill">
            <el-input v-if="answers[index].includes(option.index)"
                      v-model="fills[index][option.index]"
                      @click.native="selectItem($event, question, option)"/>
            <el-input v-else @click.native="selectItem($event, question, option)"/>
          </template>
        </el-checkbox>
      </el-checkbox-group>
      <el-input v-if="question.type === 3" type="textarea" v-model="answers[index]"
                :autosize="{ minRows: 2, maxRows: 4}"/>
      <div v-if="editable" class="body-line-height m-t-10">
        <QuestionEdit v-if="editing[index]" :question.sync="question"
                      v-on:saveQuestion="operateQuestion({ action: 'edit', index })"/>
        <div v-else class="question-options">
          <el-link type="primary"
                   @click="operateQuestion({ action: 'add', index })">在此题后插入新题</el-link>
          <div>
            <el-button size="mini" type="primary" plain
                       @click="operateQuestion({ action: 'edit', index })">编辑</el-button>
            <el-popconfirm title="确定删除这一题吗？"
                           @onConfirm="operateQuestion({ action: 'delete', index })">
              <el-button slot="reference" size="mini" type="danger"
                         plain :disabled="questions.length < 2">删除</el-button>
            </el-popconfirm>
            <el-button size="mini" type="success" plain :disabled="index === 0"
                       @click="operateQuestion({ action: 'up', index })">上移</el-button>
            <el-button size="mini" type="success" plain :disabled="index === questions.length -1"
                       @click="operateQuestion({ action: 'down', index })">下移</el-button>
          </div>
        </div>
      </div>
    </el-form-item>
    <el-form-item v-if="answering">
      <div class="flex content-center">
        <el-button type="primary" @click="onSubmit" :loading="isLoading">提交问卷</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script>
import QuestionEdit from './QuestionEdit';
import * as format from './format';

export default {
  name: 'Questions', // 问卷的问题列表
  components: { QuestionEdit },
  props: {
    questions: { // 问题列表
      type: Array,
      required: true,
    },
    editable: { // 是否允许编辑
      type: Boolean,
      required: true,
    },
    deletedQuestionsId: { // 被删除的问题的id
      type: Array,
      required: false,
    },
    answering: { // 正在作答
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      answers: format.initAnswers(this.questions), // 初始化答案格式，避免绑定错误
      fills: this.questions.map(() => ({})), // 初始化填空格式，每一题都有一个对象保存
      editing: [], // 正在编辑
      isLoading: false, // 正提交问卷
    };
  },
  methods: {
    // 生成这个问题的 ref
    initQuestionRef(question) { return `question-${question.index}`; },
    // 生成选项的 ref
    initOptionRef(question, option) { return `option-${question.index}-${option.index}`; },
    // 可填空选项，激活填空框时自动选择此项
    selectItem(el, question, option) {
      const thisOption = this.$refs[this.initOptionRef(question, option)][0].$el;
      if (thisOption.classList.value.includes('is-checked')) return;
      thisOption.click();
      this.$nextTick(() => el.target.focus());
    },
    // 对问题的操作
    operateQuestion({ action, index }) {
      if (action === 'edit') this.$set(this.editing, index, !this.editing[index]);
      else if (action === 'add') this.questions.splice(index + 1, 0, this.initNewQuestion());
      else if (action === 'delete' && this.questions.length > 1) { // 删除
        if (this.questions[index].id && this.deletedQuestionsId) {
          this.deletedQuestionsId.push(this.questions[index].id);
        }
        this.questions.splice(index, 1);
      } else if (action === 'up' && index !== 0) { // 上移
        this.questions[index] = this.questions.splice(index - 1, 1, this.questions[index])[0];
      } else if (action === 'down' && index !== this.questions.length - 1) { // 下移
        this.questions[index] = this.questions.splice(index + 1, 1, this.questions[index])[0];
      }
    },
    // 生成一道新题
    initNewQuestion() {
      return { index: new Date().getTime(), title: '', type: 1, options: format.defaultOptions };
    },
    // 提交问卷
    onSubmit() {
      const answers = format.formatAnswers(this.questions, this.answers, this.fills);
      this.isLoading = true;
      this.$api.questionnaires.answer({ qnId: this.$route.query.qn_key, answers })
        .then(() => {
          this.$message.success('提交成功');
          this.goBack();
        })
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
  },
  watch: {
    // 监听问题列表，当题目顺序或类型更新时，应该同步更新多选题绑定的answers结构，不然会报错
    questions: {
      handler() { this.$set(this, 'answers', format.initAnswers(this.questions)); },
      deep: true,
    },
  },
};
</script>

<style></style>
